package com.baizhi.cmfz.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baizhi.cmfz.annotation.AddCacheAnnotation;
import com.baizhi.cmfz.annotation.DeleteCacheAnnotation;
import com.baizhi.cmfz.dao.GuruDao;
import com.baizhi.cmfz.entity.Guru;
import com.baizhi.cmfz.service.GuruService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class GuruServiceImpl implements GuruService {
    @Autowired(required = false)
    private GuruDao guruDao;
    @Autowired
    private HttpServletRequest request;
    @Override
    @Transactional(readOnly = true)
    @AddCacheAnnotation
    public Map selectGuru(int page, int limit) {
        int offset = (page-1)*limit;
        int count = guruDao.selectCount();
        List<Guru> gurus = guruDao.selectGuru(offset, limit);
        System.out.println("所有上师信息"+gurus);
        Map map = new HashMap(4);
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        map.put("data",gurus);
        return map;
    }

    @Override
    @Transactional
    @DeleteCacheAnnotation
    public Map addGuru(Guru guru) {
        System.out.println("添加上师收参"+guru);
        int i = guruDao.addGuru(guru);
        Map map = new HashMap(2);
        if (i == 1) {
            //添加成功
            map.put("isAdd",true);
        }else {
            map.put("isAdd",false);
        }
        return map;
    }

    @Override
    @DeleteCacheAnnotation
    public Map deleteGuru(int guruId) {
        int i = guruDao.deleteGuru(guruId);
        Map map = new HashMap(2);
        if (i == 1) {
            map.put("isDelete",true);
        }else {
            map.put("isDelete",false);
        }
        return map;
    }

    @Override
    @Transactional
    @AddCacheAnnotation
    public Guru selectOneGuru(int guruId) {
        Guru guru = guruDao.selectOneGuru(guruId);
        System.out.println("修改串查询到的数据"+guru);
        return guru;
    }

    @Override
    @Transactional
    @AddCacheAnnotation
    public List<Guru> selectAllGuru() {
        List<Guru> gurus = guruDao.selectAllGuru();
        return gurus;
    }

    /*@Override
    @Transactional
    public void multiAddGuru(List<Guru> gurus) {
        guruDao.multiAddGuru(gurus);
    }*/

    @Override
    @Transactional
    @DeleteCacheAnnotation
    public Map updateGuru(Guru guru) {
        int i = guruDao.updateGuru(guru);
        Map map = new HashMap(2);
        if (i ==1) {
            map.put("isUpdate",true);
        }else {
            map.put("isUpdate",false);
        }
        return map;
    }

    /**
     * 需要对当前上师的状态进行判断 如果当前上师的状态是0 则改为1
     * 如果当前上师的状态是1 则改为0
     * @param guruId
     * @param guruStatus
     * @return
     */
    @Override
    @DeleteCacheAnnotation
    public Map updateGuruStatus(int guruId, int guruStatus) {
        int i = guruDao.updateGuruStatus(guruId,guruStatus);
        Map map = new HashMap(2);
        if (i ==1) {
            map.put("isUpdataStatus",true);
        }else {
            map.put("isUpdataStatus",false);
        }
        return map;
    }

    /**
     * 在service中进行文件内容映射成为对象，完成上师的批量添加
     * @param filePath
     * @return
     */
    @Override
    @Transactional
    @DeleteCacheAnnotation
    public Map multiAddGuru(String filePath) throws IOException {
        //读取文件获取流
        FileInputStream inputStream = new FileInputStream(filePath);
        //poi 处理流获取文件对象
        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
        //根据下标获取表
        HSSFSheet sheet = workbook.getSheetAt(0);
        //获取到最后一行的下标，遍历行数 获取数据
        int lastRowNum = sheet.getLastRowNum();
        //先创建一个集合 用来存放每行数据对应的上师
        List<Guru> gurus = new ArrayList<>();
        for (int i = 1; i <= lastRowNum; i++) {
            HSSFRow row = sheet.getRow(i);
            //获取每个单元格的数据 由于是添加不需要id
            String name = row.getCell(1).getStringCellValue();
            String img = row.getCell(2).getStringCellValue();
            String nickName = row.getCell(3).getStringCellValue();
            String status = row.getCell(4).getStringCellValue();
            //将一行的数据封装到对象中
            Guru guru = new Guru();
            guru.setGuruName(name);
            guru.setGuruImage(img);
            guru.setGuruNickname(nickName);
            guru.setGuruStatus(Integer.parseInt(status));
            gurus.add(guru);
        }
        //批量添加数据库
        int i = guruDao.multiAddGuru(gurus);
        Map map =  new HashMap(2);
        if (i == gurus.size()) {
            map.put("isMultiAdd", true);
        }else {
            map.put("isMultiAdd", false);
        }
        return map;
    }

    @Override
    @Transactional
    public Map downLoadGuru() throws IllegalAccessException, IOException {
        //在这里做文件的导出工作
        //获取数据库中所有的数据
        List<Guru> gurus = guruDao.selectAllGuru();
        //使用easyPOI时对数据做一定的处理 需要给文件拼接上项目名
        //String contextPath = request.getContextPath();
        for (Guru guru : gurus) {
            String guruImage = guru.getGuruImage();
            String newGuruImage = "http://localhost:8989/cmfz"+guruImage;
            //System.out.println(newGuruImage);
            guru.setGuruImage(newGuruImage);
        }
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("上师信息数据","guru"),
                Guru.class, gurus);
        //创建文件写入到磁盘文件中
        /*
        poi原始的数据导出
        //创建一个文件对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //获取一个表格
        HSSFSheet sheet = workbook.createSheet("guru");
        //将表格的头部信息封装为一个数组
        String[] guruHeader ={"上师编号","上师名称","上师图片地址","上师法号","上师状态"};
        HSSFRow row = sheet.createRow(0);
        for (int i = 0;i < guruHeader.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(guruHeader[i]);
        }
        //通过反射的方式进行优化
        for (int i = 0; i < gurus.size(); i++) {
            //获取一个行对象
            HSSFRow sheetRow = sheet.createRow(i + 1);
            //获取到对象
            Guru guru = gurus.get(i);
            //根据对象利用反射获得类对象
            Class<? extends Guru> guruClass = guru.getClass();
            //根据类对象获取到存放对象属性的数组
            Field[] fields = guruClass.getDeclaredFields();
            for (int j = 0; j < fields.length; j++) {
                //遍历属性 获取属性值 循环创建单元格 并且给单元格赋值
                //类中的私有属性 需要设置为暴力访问
                fields[j].setAccessible(true);
                HSSFCell cell = sheetRow.createCell(j);
                cell.setCellValue(fields[j].get(guru).toString());
            }
        }*/
        String name = "E:\\poi\\guru.xlsx";
        workbook.write(new FileOutputStream(name));
        Map map = new HashMap(2);
        map.put("isDownLoad",true);
        map.put("name",name);
        return map;
    }
}
